﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using AutoTLBB.Utilites;

namespace AutoTLBB {
    public partial class AutoTLBB : Form {
        List<CharacterModel> m_lstCharacterModel = new List<CharacterModel>(3);
        CharacterModel CurrentChar {
            get {
                if (m_lstChar.Items.Count == 0 || m_lstChar.SelectedIndex < 0) {
                    return new CharacterModel();
                }
                return m_lstCharacterModel.Find(x => x.Name == (string)m_lstChar.SelectedItem);
            }
        }
        public bool ShutDownPc { get { return m_cbkShutdownPC.Checked; } }
        public int AllGame { get; set; }
        public bool IsNotice { get; set; }
        public string SoundPath = @"\Files\TLBB.mp3";
        public string DefaultSoundPath;
        private bool IsPlaySound { get; set; }
        TaskbarNotifier m_noticeBox;
        public AutoTLBB() {
            InitializeComponent();
            m_characterInfoConfig.RequestCloseGame += new EventHandler(OnClosedGame);
        }
        void OnClosedGame(object sender, EventArgs e) {
            string chars = (string)m_lstChar.SelectedItem;
            CharacterModel model = CurrentChar;
            GameUtilities.TurnOffGame(model.ProcessId);
            m_lstCharacterModel.Remove(model);
            m_lstChar.Items.Remove(chars);
        }
        void ClosedNoticed(object sender, EventArgs e) {
            this.IsNotice = false;
        }
        private void ReloadCharInfo() {
            m_characterInfoConfig.SetDataContext(CurrentChar);
        }
        private void SelectedCharacterChanged(object sender, EventArgs e) {
            ReloadCharInfo();
        }
        private void Refresh() {

            Process[] processesByName = Process.GetProcessesByName("Game");
            m_lstCharacterModel.Clear();
            m_lstChar.Items.Clear();

            foreach (Process process in processesByName) {
                string nameChar = GameUtilities.GetCharacterName(process.Id);
                string charId = GameUtilities.GetID(process.Id);
                CharacterModel character = XmlSerializeHelper.DeSerializeUserConfig(charId);

                if (character == null) {
                    character = new CharacterModel();
                    character.ID = charId;
                }
                character.Name = nameChar;
                character.ProcessId = process.Id;
                character.WindowHandle = process.MainWindowHandle;
                if (m_lstCharacterModel.Find(x => x.ID == character.ID) == null) {
                    m_lstCharacterModel.Add(character);
                    this.m_lstChar.Items.Add(nameChar);
                }
                character.PropertyChanged += new PropertyChangedEventHandler(UserModelChanged);
            }
        }
        private void UserModelChanged(object sender, PropertyChangedEventArgs e) {
            CharacterModel model = (CharacterModel)sender;
            if (model != null && model.ID == CurrentChar.ID) {
                m_characterInfoConfig.RefreshStartButton();
            }
        }
        private void RunAuto(object sender, EventArgs e) {
            if (ShutDownPc && m_lstCharacterModel.Count == 0) {
                ShutDownPC.Shutdown2();
            }
            foreach (CharacterModel model in m_lstCharacterModel) {
                if (model.IsRunning) {
                    if (GameUtilities.GetRun(model.ProcessId) == 1) {
                        if (GameUtilities.IsTarget(model.ProcessId) == 0 && model.Radius != null && model.Radius.IsSelected) {
                            model.IsRunning = false;
                            if (CheckUserRadius(model)) {
                                this.ShowNotice("Thông báo!", model.Name + " ra ngoài bán kính train !!!");
                            }
                        } else {
                            model.IsRunning = true;
                        }
                    } else {
                        model.IsRunning = true;
                    }
                }
                if (this.IsNotice) {
                    if (IsPlaySound) {
                        GameUtilities.PlaySimpleSound(SoundPath);
                    }
                } else {
                    GameUtilities.StopSimpleSound();
                }

                if (model.IsRunning && model.Name != string.Empty) {
                    if (GameUtilities.HasAutoQuestion(model.ProcessId) == 1) {
                        if (!this.IsNotice) {
                            ReadMemory.ShowWindow(model.WindowHandle, 9);
                            ShowNotice("Thông báo", model.Name + " cần trả lời câu hỏi auto!");
                            this.IsNotice = true;
                            model.ShouldAlert = true;
                            model.IsHideGame = false;
                            model.TimeAutoHandle = DateTime.Now;
                            if (this.CurrentChar == model) {
                                m_characterInfoConfig.UpdateHideGame(false);
                            }
                        }
                    }
                    if (model.ShouldAlert && GameUtilities.HasAutoQuestion(model.ProcessId) == 0) {
                        GameUtilities.StopSimpleSound();
                        this.HideNotice();
                        this.IsNotice = false;
                        model.ShouldAlert = false;
                    }
                    RunAutoForChar(model);
                }
            }
        }
        private void ShowNotice(string charname, string messa = "đang gặp nguy hiểm!") {
            m_noticeBox.Show(charname, messa, 100, 60000, 500);
        }
        private void HideNotice() {
            m_noticeBox.Hide();
            GameUtilities.StopSimpleSound();
        }
        private void RunAutoForChar(CharacterModel model) {
            if (!model.IsRunning) { return; }
            #region Basic Attack
            //GameUtilities.PlaySimpleSound(DefaultSoundPath);
            if (model.BasicSkill.IsSelected) {
                if (!model.IsTarget) {
                    GameUtilities.PressKey(model.WindowHandle, model.Target);
                }
                if (model.HitStyle == HitStyle.Ngoai) {
                    int num = 0;
                    if (model.IsTarget) {
                        GameUtilities.PressKey(model.WindowHandle, model.BasicSkill.SkillKey);
                        if (GameUtilities.GetBossBlood(model.ProcessId) > 0 && (GameUtilities.GetBossBlood(model.ProcessId) < 0x3f800000)) {
                            num = GameUtilities.GetBossBlood(model.ProcessId);
                        } else {
                            num = GameUtilities.GetMonsterBlood(model.ProcessId);
                        }
                    }
                    if (num < 1) {
                        GameUtilities.PressKey(model.WindowHandle, model.Target);
                    }
                } else if (model.HitStyle == HitStyle.Noi) {
                    if (GameUtilities.IsHit(model.ProcessId) == 0) {
                        GameUtilities.PressKey(model.WindowHandle, model.Target);
                        if (model.IsTarget) {
                            GameUtilities.PressKey(model.WindowHandle, model.BasicSkill.SkillKey);
                        }
                    }
                } else {
                    if (model.TimeDelayToAttack == 0 || (DateTime.Now.Subtract(model.TimeAutoHandle).TotalSeconds > model.TimeDelayToAttack)) {
                        GameUtilities.PressKey(model.WindowHandle, model.Target);
                        GameUtilities.PressKey(model.WindowHandle, model.BasicSkill.SkillKey);
                    }
                }
            }
            #endregion Basic Attack
            #region Attack by Skill
            if (model.Skill1.IsSelected && (model.Skill1.CanHandle)) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill1.SkillKey);
            }
            if (model.Skill2.IsSelected && model.Skill2.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill2.SkillKey);
            }
            if (model.Skill3.IsSelected && model.Skill3.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill3.SkillKey);
            }
            if (model.Skill4.IsSelected && model.Skill4.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill4.SkillKey);
            }
            if (model.Skill5.IsSelected && model.Skill5.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill5.SkillKey);
            }
            if (model.Skill6.IsSelected && model.Skill6.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill6.SkillKey);
            }
            if (model.Skill7.IsSelected && model.Skill7.CanHandle) {
                GameUtilities.PressKey(model.WindowHandle, model.Skill7.SkillKey);
            }

            if ((model.AlertBlood != null && model.AlertBlood.IsSelected &&
                ((GameUtilities.GetCharacterBlood(model.ProcessId) < model.AlertBlood.Value) &&
                (GameUtilities.GetCharacterBlood(model.ProcessId) != 0))) && !this.IsNotice) {
                this.ShowNotice("Thông báo", model.Name + " máu đang nguy hiểm!");
                this.IsNotice = true;
                model.ShouldAlert = true;
            }
            if (model.Radius != null && model.Radius.IsSelected) {
                if ((Math.Ceiling(GameUtilities.RadiusModel(model)) > model.Radius.Value) && (Math.Ceiling(GameUtilities.RadiusModel(model)) < (model.Radius.Value + 20))) {
                    GameUtilities.PressKey(model.WindowHandle, model.Target);
                    GameUtilities.PressKey(model.WindowHandle, model.BasicSkill.SkillKey);
                }
                if (Math.Ceiling(GameUtilities.RadiusModel(model)) > (model.Radius.Value + 20)) {
                    this.ShowNotice("Thông báo", model.Name + " ra ngoài bán kính train!");
                    this.IsNotice = true;
                    model.ShouldAlert = true;
                    model.IsRunning = false;
                }
            }
            if (model.EatingBlood != null && (GameUtilities.GetCharacterBlood(model.ProcessId) < model.EatingBlood.Value)) {
                FeedPetFullBlood(model);
                GameUtilities.PressKey(model.WindowHandle, model.EatingBlood.SkillKey);
            }
            if (model.EatingMana != null && model.EatingMana.IsSelected &&
                (GameUtilities.GetCharacterMana(model.ProcessId) < model.EatingMana.Value)) {
                FeedPetFullBlood(model);
                GameUtilities.PressKey(model.WindowHandle, model.EatingMana.SkillKey);
            }
            if (model.PetFeed != null && model.PetFeed.IsSelected && (GameUtilities.GetPetBlood(model.ProcessId) < model.PetFeed.Value)) {
                GameUtilities.PressKey(model.WindowHandle, model.PetFeed.SkillKey);
            }
            if ((model.ShutdownGameAfterQuestion != null && model.ShutdownGameAfterQuestion.IsSelected &&
                ((GameUtilities.HasAutoQuestion(model.ProcessId) == 1) ||
                (model.ShutdownGameWhenBlood != null && model.ShutdownGameWhenBlood.IsSelected &&
                GameUtilities.GetCharacterBlood(model.ProcessId) < model.ShutdownGameWhenBlood.Value))) &&
                (DateTime.Now.Subtract(model.TimeAutoHandle).Seconds > model.ShutdownGameAfterQuestion.Value) && model.ShouldAlert) {
                ReadMemory.ShowWindow(model.WindowHandle, 9);
                model.IsRunning = false;
                model.IsHideGame = false;
                m_lstChar.Items.Remove(model.Name);
                m_lstCharacterModel.Remove(model);
                GameUtilities.TurnOffGame(model.ProcessId);
                Thread.Sleep(3000);
                //this.buttonRefreshGame.PerformClick();
            }
            #endregion
        }
        private static void FeedPetFullBlood(CharacterModel model) {
            if (model.EatingWhenBloodOfPet != null && model.EatingWhenBloodOfPet.IsSelected && model.EatingWhenBloodOfPet.CanHandle) {
                int count = 0;
                int maxhpPet = GameUtilities.GetMaxPetBlood(model.ProcessId);
                while (count < 10 && maxhpPet >= GameUtilities.GetPetBlood(model.ProcessId) + 50) {
                    GameUtilities.PressKey(model.WindowHandle, model.EatingWhenBloodOfPet.SkillKey);
                    count++;
                }
            }
        }
        private bool CheckUserRadius(CharacterModel model) {
            if (model.Radius != null && model.Radius.IsSelected) {
                if ((Math.Ceiling(GameUtilities.RadiusModel(model)) > model.Radius.Value) && (Math.Ceiling(GameUtilities.RadiusModel(model)) < (model.Radius.Value + 20))) {
                    GameUtilities.PressKey(model.WindowHandle, model.Target);
                    GameUtilities.PressKey(model.WindowHandle, model.BasicSkill.SkillKey);
                }
                if (Math.Ceiling(GameUtilities.RadiusModel(model)) > (model.Radius.Value + 30)) {
                    this.ShowNotice("Thông báo", model.Name + " ra ngoài bán kính train!");
                    this.IsNotice = true;
                    model.ShouldAlert = true;
                    model.IsRunning = false;
                    return false;
                }
            }
            return true;
        }
        private void OnBrowserSound(object sender, EventArgs e) {
            using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
                openFileDialog.InitialDirectory = Application.StartupPath;
                openFileDialog.Filter = "Mp3 files (*.mp3)|*.mp3";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK) {
                    SoundPath = openFileDialog.FileName;
                    m_txtFilePath.Text = SoundPath;
                }
            }
        }
        private void PlaySoundCheckedChanged(object sender, EventArgs e) {
            IsPlaySound = m_chkIsPlaySound.Checked;
        }
        private void RefreshDataClick(object sender, EventArgs e) {
            Refresh();
        }
        private void DelayChanged(object sender, EventArgs e) {
            double second = Convert.ToDouble(m_cbxDelayTime.Text);
            m_autoTimer.Interval = Convert.ToInt32(second * 1000);
        }
        private void AutoTLBB_Load(object sender, EventArgs e) {
            SplashScreen about = new SplashScreen();
            about.Show();

            DefaultSoundPath = Application.StartupPath + SoundPath;
            SoundPath = DefaultSoundPath;
            m_txtFilePath.Text = DefaultSoundPath;
            #region Init Notifier
            m_noticeBox = new TaskbarNotifier();
            m_noticeBox.SetBackgroundBitmap(Properties.Resources.skin, Color.FromArgb(255, 0, 255));
            m_noticeBox.SetCloseBitmap(Properties.Resources.close, Color.FromArgb(255, 0, 255), new Point(127, 8));
            m_noticeBox.TitleRectangle = new Rectangle(40, 9, 70, 25);
            m_noticeBox.ContentRectangle = new Rectangle(8, 41, 133, 68);
            m_cbxDelayTime.SelectedItem = "0.5";
            #endregion Init Notifier

            IsPlaySound = true;
            m_chkIsPlaySound.Checked = IsPlaySound;
            m_noticeBox.CloseClick += new EventHandler(ClosedNoticed);
            m_lstChar.Items.Clear();
            Refresh();
            if (m_lstChar.Items.Count > 0) {
                m_lstChar.SelectedIndex = 0;
            }
            ReloadCharInfo();
            for (int i = 0; i < 5; i++) {
                about.SetProgress(20);
                Thread.Sleep(TimeSpan.FromSeconds(0.3));
            }
            about.Close();
            m_autoTimer.Start();
        }
        private void OnAboutClick(object sender, EventArgs e) {
            About about = new About();
            about.ShowDialog();
        }
        protected override void OnClosed(EventArgs e) {
            foreach (CharacterModel model in m_lstCharacterModel) {
                if (model.IsHideGame) {
                    GameUtilities.ShowGame(model.WindowHandle, true);
                }
            }
            base.OnClosed(e);
        }
    }
}
